<?php

class Tree
{

   public $tree = [];

    /**
     * 构建树
     * @param $arr
     * @return void
     */
   public function insert($arr){
       foreach($arr as $value){
           $tree = $this->tree;
           $this->tree = &$tree;
           $strArr =  $this->split($value);
           foreach ($strArr as $item){
                  if(!isset($tree[$item])){
                       $tree[$item] = [];
                  }
                      $tree = &$tree[$item];
           }
           $tree['isEnd'] = true;
           unset($tree);
       }
   }
   public function split($str){
       $arr = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
       return $arr;
   }
    public function check ($str){
           $text= $str;
           $strArr = $this->split($str);
           $length = count($strArr);
           $onArr = [];
           for($i=0;$i<$length;$i++){
                    if(!isset($this->tree[$strArr[$i]])){
                        continue;
                    }
                     $treeNode = $this->tree[$strArr[$i]];
                     $strIndex= [];
                     $strIndex[] = $i;
                    for ($j=$i+1;$j<$length;$j++){
                        if(!isset($treeNode[$strArr[$j]])){
                            break;
                        }
                        $strIndex[] = $j;
                        $treeNode = $treeNode[$strArr[$j]];
                    }

                    $str = '';
                    if(isset($treeNode['isEnd'])){
                         foreach ($strIndex as $dex){
                              $str.=$strArr[$dex];
                         }
                         $onArr[] = $str;
                    }
           }
           foreach ($onArr as $ll){
            echo  count($ll);
            $text = str_replace($ll,'****',$text);
           }
        echo $text;


    }
}

 $tree = new Tree;
$arr = ['大傻瓜','傻瓜','大傻','大傻b'];
$tree->insert($arr);
$text = '你就是大傻瓜傻瓜，你就是大傻b!';
$tree->check($text);



